import Taro, { Component } from '@tarojs/taro'
import { AtSearchBar } from 'taro-ui'
import classNames from 'classnames'
import PropsType from 'prop-types'
import { View } from '@tarojs/components'
// import http from '@/api'
import commonUtils from '@/common/index'
import '../styles/map.scss'

export default class DMap extends Component {

  constructor(props) {
    super(props)
    this.state = {
      map: null,
      searchInfo: '',
      currentIp: {}
    }
  }

  componentDidMount() {
    let { address } = this.$router.params

    this.loadScript(address).then(map => {
      this.setState({ map })
    })
  }
  mapLoad(map, searchInfo) {
    let _that = this

    // 添加带有定位的导航控件,
    const navigationControl = new BMap.NavigationControl({
      // 靠左上角位置
      anchor: BMAP_ANCHOR_TOP_LEFT,
      // LARGE类型
      type: BMAP_NAVIGATION_CONTROL_LARGE,
      // 启用显示定位
      enableGeolocation: true,
      enableHighAccuracy: true
    });


    map.addEventListener('click', function (e, ev) {
      map.centerAndZoom(new BMap.Point(e.point.lng, e.point.lat), 15);
      _that.setState({ map, searchInfo }, () => {
        _that.positionHandle(map)
        _that.serachHandle(map, `${e.point.lng},${e.point.lat}`)
      })

    });

    map.addControl(navigationControl);

    _that.setState({ map, searchInfo }, () => {
      _that.state.searchInfo

      _that.positionHandle(map)
      _that.serachHandle(map, `${searchInfo}`)
    })
  }
  //异步加载地图库函数文件
  loadScript(info) {
    const _that = this
    return new Promise((res, rej) => {
      window.__init__ = () => {
        // 百度地图API功能
        const map = new BMap.Map("container_map");

        //获取当前坐标
        new BMap.Geolocation().getCurrentPosition(
          function (r) {

            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              //通过Geolocation类的getStatus()可以判断是否成功定位。
              let currentIp = r.point
              _that.setState({
                currentIp: currentIp
              }, () => {
              })
              // https://api.map.baidu.com/location/  @params ip
              // map.centerAndZoom(new BMap.Point(113.3594012300, 23.1279723500), 15);
              let addr = r.address, searchInfo = ''
              searchInfo += addr.province;
              searchInfo += addr.city;
              searchInfo += addr.district;
              searchInfo += addr.street;
              searchInfo += addr.street_number;
              // info = info || searchInfo
              if (!info) {
                map.centerAndZoom(new BMap.Point(currentIp.lng, currentIp.lat), 15);
                info = searchInfo
                // http.ipLocation().then(res=>{
                // 	info = res.rgc.result.formatted_address
                // 		 _that.mapLoad(map,info)
                // })
              } else {

              }
              _that.mapLoad(map, info)

              res(map)
            }
          },

          { enableHighAccuracy: true }

        );

      }
      // require('@/common/').default.MapappendToBodyFn()
      //创建script标签
      var script = document.createElement("script");
      //设置标签的type属性
      script.type = "text/javascript";

      //设置标签的链接地址
      script.src = "//api.map.baidu.com/api?v=2.0&ak=ePq0Qz5lmCsQgyLzu4DHaDxg0YPpLBuk&callback=__init__&time=" + new Date().getTime();
      //添加标签到dom
      document.body.appendChild(script);
    })

  }

  // 定位事件
  positionHandle(map) {
    const _that = this
    // 添加定位控件
    var geolocationControl = new BMap.GeolocationControl({
      anchor: BMAP_ANCHOR_TOP_RIGHT
    });
    //
    geolocationControl.addEventListener("locationSuccess", function (e) {
      const { province = '', city = '', district = '', street = '', streetNumber = '' } = e.addressComponent
      // 定位成功事件
      var address = '';
      address += province;
      address += city;
      address += district;
      address += street;
      address += streetNumber;
      map.centerAndZoom(address, 11)
      _that.setState({
        searchInfo: address,
        map
      }, () => {
        _that.serachHandle(map)
      })
    });
    geolocationControl.addEventListener("locationError", function (e) {
      // 定位失败事件
      alert(e.message);
    });
    map.addControl(geolocationControl);
  }

  // 搜索事件
  serachHandle(_map, searchInfos) {

    let { searchInfo = '', map, currentIp } = this.state
    let { lat, lng } = currentIp

    if (!_map) {
      _map = map
    }
    searchInfo = searchInfos || searchInfo
    _map.centerAndZoom(searchInfo, 11)

    // var point = new BMap.Point(+searchInfos.split(',')[0],+searchInfos.split(',')[1]);  // 创建点坐标
    // _map.centerAndZoom(point, 15)
    // map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);

    const _that = this
    var options = {
      renderOptions: { map: map, panel: "r-result" },
      onSearchComplete: function (results) {
        // 判断状态是否正确
        if (local.getStatus() == BMAP_STATUS_SUCCESS) {
          const { province = '', city = '' } = results
          var s = [];
          for (var i = 0; i < results.getCurrentNumPois(); i++) {
            let point = results.getPoi(i).point
            s.push({
              title: results.getPoi(i).title,
              desc: results.getPoi(i).address,
              region: province + city,
              point,
              distance: commonUtils.getDistance(lat, lng, point.lat, point.lng) + 'km'

            })
          }
          //
          _that.props.serachHandle && _that.props.serachHandle(s)
        }
      }
    };
    let myKeys = [`${searchInfo}`]
    var local = new BMap.LocalSearch(_map, options);
    local.search(`${searchInfo}`);
    // local.searchInBounds(myKeys, _map.getBounds());
  }

  onChangeHandle(value) {
    this.setState({
      searchInfo: value
    }, () => this.serachHandle(''))

  }


  render() {
    const {
      className
    } = this.props
    const {
      searchInfo
    } = this.state
    return (
      <View className={classNames('b_map', className)}>
        <AtSearchBar className='b_map__search'

          placeholder='搜索地点' value={searchInfo} onChange={this.onChangeHandle.bind(this)} onActionClick={this.serachHandle.bind(this, '')}></AtSearchBar>
        <View id='container_map'></View>
      </View>
    )
  }
}

DMap.defaultProps = {
  search: '',
  className: '',
  onPositionHandle: () => { },
  serachHandle: () => { }
}

DMap.PropsType = {
  search: PropsType.string,
  className: PropsType.oneOfType[PropsType.string, PropsType.object],
  onPositionHandle: PropsType.func,
  serachHandle: PropsType.func
}
